#include "cDataSourceCVS.h"

cDataSourceCVS::cDataSourceCVS(void)
{

}

cDataSourceCVS::cDataSourceCVS(const char* Name, const char* data)
{
	// set name
	DataSourceName = Name;
	ParseData(data);

}

cDataSourceCVS::~cDataSourceCVS(void)
{
}

const char* cDataSourceCVS::GetDataSourceName(void) const
{
	return DataSourceName.c_str();
}

int cDataSourceCVS::GetRowCount(void) const
{
	return Data.size();
}

int cDataSourceCVS::GetColumnNumber(const char* Column) const
{
	int N = -1;

	for(unsigned int i=0; i< ColumnName.size(); i++)
	{
		if(ColumnName[i] == Column)
			N = i;
	}
	return N;
}

const char* cDataSourceCVS::GetValue(unsigned int Column,unsigned int Row) const
{
	if(Column > ColumnName.size())
		return NULL;

	if(Row > Data.size())
		return NULL;
	
	
	return Data[Row][Column].c_str();
}


const char* cDataSourceCVS::GetValue(const char* ColumnName, int Row) const
{
	return "";
}

int cDataSourceCVS::ParseData(const char* data)
{
	vector<string> Row = GetSubStringBySeparator(data,'\n');
	
	vector<string> Column = GetSubStringBySeparator(Row[0],',');
	if(Column.empty())
	{
		return -1;
	}

	ColumnName = Column;

	for(unsigned int i = 1; i< Row.size();i++)
	{
		vector<string> temp = GetSubStringBySeparator(Row[i],',');
		if( temp.size() != Column.size())
		{
			return -1;
		}
		Data.push_back(temp);
	}
	
	return 0;
}

const vector<string> cDataSourceCVS::GetSubStringBySeparator(string line,char separator)
{
	vector<string> OutData;
	
	unsigned int stop = line.find(separator);
	unsigned int start = 0;

	while(start < line.size())
	{
		string value = line.substr(start,stop-start);
		if(!value.empty())
			OutData.push_back(value);

		// next record
		start = stop + 1;
		stop = line.find(separator,start + 1);
		if(stop == string::npos)
		{
			stop = line.size();
		}
		
		
	}

	return OutData;

}